package org.jf.tool.fx.jftoolfx.format.controller;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Spinner;
import javafx.scene.control.TextArea;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.jf.tool.fx.jftoolfx.common.BaseController;

import java.io.StringWriter;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * @author jifeng_zhang
 * @date 2025/9/22 下午1:15
 */
public class XmlFormatController extends BaseController {
    @FXML
    public Spinner<Integer> indentSize;
    @FXML
    private TextArea textArea;
    @FXML
    private TextArea resultArea;

    @Override
    protected void init(URL url, ResourceBundle resourceBundle) {
    }

    @FXML
    private void format() {
        XMLWriter writer = null;
        try {
            String xmlString = textArea.getText();
            // 1. 将字符串解析为 Document 对象
            Document document = DocumentHelper.parseText(xmlString);
            // 2. 创建漂亮的打印格式
            OutputFormat format = OutputFormat.createPrettyPrint();
            // 设置缩进
            format.setIndentSize(indentSize.getValue());
            // 可选：是否抑制 XML 声明
            format.setSuppressDeclaration(false);
            // 3. 将格式化后的内容写入 StringWriter
            StringWriter sw = new StringWriter();
            writer = new XMLWriter(sw, format);
            writer.write(document);
            resultArea.setText(sw.toString());
        } catch (Exception e) {
            resultArea.setText("XML 格式化失败：" + e.getMessage());
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception e) {
                }
            }
        }
    }

    @FXML
    private void clear() {
        textArea.setText("");
        resultArea.setText("");
    }

    @FXML
    private void copy(ActionEvent event) {
        copy(resultArea.getText());
    }
}
